package com.basker.pisces.core.operator.handler;

import java.lang.reflect.Array;
import java.text.MessageFormat;

import com.basker.pisces.core.operator.CompareOperator;
import com.basker.pisces.core.utils.ConvertUtils;
import com.basker.pisces.exception.ExceptionFactory;

public class SqlNumberRangeCompareOperatorHandler extends SqlCompareOperatorHandler {

    /**
     * 获取数字范围的条件表达式
     *
     * @return 如果起始和结束数字都有，则返回 "字段 BETWEEN ? AND ?";如果只存在一个，则返回"字段 >= ?"或者"字段 <= ?"
     */
    @Override
    public String getConditionExpression(String fieldName, CompareOperator op, Object value, boolean isParameterExp) {
        Object[] nums = (Object[]) value;

        Object from = nums[0];
        Object to = nums[1];

        if (isParameterExp) {
            if (from != null && to != null) {
                return MessageFormat.format("{0}.{1} BETWEEN ? AND ?", HOST_VAR, fieldName);
            } else if (from != null) {
                return MessageFormat.format("{0}.{1} >= ?", HOST_VAR, fieldName);
            } else {
                return MessageFormat.format("{0}.{1} <= ?", HOST_VAR, fieldName);
            }
        } else {
            if (from != null && to != null) {
                return MessageFormat.format("{0}.{1} BETWEEN {2} AND {3}", HOST_VAR, fieldName, from, to);
            } else if (from != null) {
                return MessageFormat.format("{0}.{1} >= {2}", HOST_VAR, fieldName, from);
            } else {
                return MessageFormat.format("{0}.{1} <= {2}", HOST_VAR, fieldName, to);
            }
        }
    }

    /**
     * 传入的条件值必须是一个长度为2的数组，分别表示起始数量和结束数量，可以其中有一个值为null
     */
    @Override
    public Object updateValue(Object value) {
        if (value == null) {
            return null;
        }

        Object[] values = ConvertUtils.convert2Array(value);
        if (values.length == 0) {
            return null;
        }

        if (values.length == 1) {
            Object from = Array.get(values, 0);
            if (from == null) {
                return null;
            }

            return new Object[]{from, null};
        }

        if (values.length == 2) {
            Object from = Array.get(values, 0);
            Object to = Array.get(values, 1);

            if (from == null && to == null) {
                throw ExceptionFactory.createRuntimeException(
                        "pisces-core.SqlNumberRangeCompareOperatorHandler.updateValue",
                        "formNumber and toNumber is all null");
            }

            return new Object[]{from, to};
        }

        return null;
    }

}
